<template>
  <div class="goods-sku">
    <dl v-for="(item, idx) in goodsData.specs" :key="idx">
      <dt>{{ item.name }}</dt>
      <dd>
        <template v-for="val in item.values" :key="val.name">
          <img
            v-if="val.picture"
            :class="{ selected: val.selected, disabled: val.disabled }"
            @click="clickSpecs(item, val)"
            :src="val.picture"
            :title="val.name"
          />
          <span
            v-else
            :class="{ selected: val.selected, disabled: val.disabled }"
            @click="clickSpecs(item, val)"
            :src="val.picture"
            >{{ val.name }}</span
          >
        </template>
      </dd>
    </dl>
  </div>
</template>
<script>
import getPowerSet from '@/vender/power-set'
const spliter = '*'
// 根据skus数据得到路径字典对象
const getPathMap = (skus) => {
  const pathMap = {}
  skus.forEach((sku) => {
    // 1. 过滤出有库存有效的sku
    if (sku.inventory) {
      // 2. 得到sku属性值数组 ['黑色','中国', '10cm']
      const specs = sku.specs.map((spec) => spec.valueName)
      // 3. 得到sku属性值数组的子集
      //    [[''],['黑色'],['中国'],['10cm'],['黑色','中国'],... ]
      const powerSet = getPowerSet(specs)
      // 4. 设置给路径字典对象
      powerSet.forEach((set) => {
        const key = set.join(spliter)
        if (pathMap[key]) {
          // 已经有key往数组追加
          pathMap[key].push(sku.id)
        } else {
          // 没有key设置一个数组
          pathMap[key] = [sku.id]
        }
      })
    }
  })
  return pathMap
}
/**
 *更新按钮的禁用状态
 */
const updateDisabledStatus = (pathMap, specs) => {
  // 1. 获取当前用户的选择
  const _selectedArr = getSelectedArr(specs)
  console.log('当前用户选择的条件是', _selectedArr)
  specs.forEach((spec, idx) => {
    const selectedArr = [..._selectedArr]
    spec.values.forEach((btn) => {
      console.log('按钮的名字', btn.name)
      // 2. 已经选中的按钮不用判断
      if (btn.selected) {
        return
      }
      // 3. 假设它能选，更新选中之后的条件
      selectedArr[idx] = btn.name
      // 4. 过滤掉undefined得到key
      const key = selectedArr.filter((v) => v).join(spliter)
      console.log('当前用户选择的条件是', selectedArr, key)
      // 5. 确定 禁用状态
      btn.disabled = !pathMap[key]
    })
  })
}
/**
 * 获取用户当前的选择
 */
const getSelectedArr = (specs) => {
  return specs.map((spec) => {
    const selectedVal = spec.values.find((val) => val.selected)
    return selectedVal ? selectedVal.name : undefined
  })
}
/**
 * 根据skuId还原用户选中的规格
 */
// 根据skuId还原用户选中的规格
const initSelectedStatus = (goodsData, skuId) => {
  // 1. 找到选中的具体的规格
  const sku = goodsData.skus.find(sku => sku.id === skuId)
  // 2. 设置对应的按钮的selected为true
  if (sku) {
    const selectArr = sku.specs.map(it => it.valueName)
    console.log('找到选中的具体的规格', selectArr, sku)
    // ["黑色", "中国", "10cm"]
    goodsData.specs.forEach((spec, idx) => {
      spec.values.forEach(value => {
        value.selected = (value.name === selectArr[idx])
      })
    })
  }
}
export default {
  name: 'GoodsSku',
  props: {
    goodsData: { type: Object, default: () => ({ specs: [], skus: [] }) },
    skuId: { type: String, default: '' }
  },
  setup (props, { emit }) {
    const clickSpecs = (item, val) => {
      // 如果是disabled，则不做处理
      if (val.disabled) {
        return
      }
      if (val.selected) {
        val.selected = false
      } else {
        // 1.全部不选
        item.values.forEach((it) => (it.selected = false))
        // 2.自己选
        val.selected = true
      }
      // 在次更新规格按钮的disabled
      updateDisabledStatus(pathMap, props.goodsData.specs)
      tryEmit()
    }

    // 通知父组件
    const tryEmit = () => {
      const sku = {}
      const curSelected = getSelectedArr(props.goodsData.specs)
      if (curSelected.filter(v => v).length === curSelected.length) {
        const key = curSelected.join(spliter)
        const skuId = pathMap[key][0]
        const skuObj = props.goodsData.skus.find(it => it.id === skuId)

        console.log('选全了', skuId)
        sku.skuId = skuId
        sku.price = skuObj.price
        sku.oldPrice = skuObj.oldPrice
        sku.inventory = skuObj.inventory
        sku.specsText = curSelected.join(',')
      }
      emit('change', sku)
    }
    const pathMap = getPathMap(props.goodsData.skus)
    console.log('路径查询字典', pathMap)
    // 初始更新disabled
    updateDisabledStatus(pathMap, props.goodsData.specs)
    // 根据传入的skuId默认选中规格按钮
    initSelectedStatus(props.goodsData, props.skuId)

    return { clickSpecs }
  }
}
</script>
<style scoped lang="less">
.sku-state-mixin () {
  border: 1px solid #e4e4e4;
  margin-right: 10px;
  cursor: pointer;
  &.selected {
    border-color: @xtxColor;
  }
  &.disabled {
    opacity: 0.6;
    border-style: dashed;
    cursor: not-allowed;
  }
}
.goods-sku {
  padding-left: 10px;
  padding-top: 20px;
  dl {
    display: flex;
    padding-bottom: 20px;
    align-items: center;
    dt {
      width: 50px;
      color: #999;
    }
    dd {
      flex: 1;
      color: #666;
      > img {
        width: 50px;
        height: 50px;
        .sku-state-mixin ();
      }
      > span {
        display: inline-block;
        height: 30px;
        line-height: 28px;
        padding: 0 20px;
        .sku-state-mixin ();
      }
    }
  }
}
</style>
